/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package main.Tree;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import main.Resulter;

/**
 *
 * @author Pacific
 */
public class NodeTree {
    private Resulter resulter;
    private ArrayList<NodeTree> childs = new ArrayList<>() ;

    public NodeTree(Resulter resulter) {
        this.resulter = resulter;
    }

    
    public Resulter getResulter() {
        return resulter;
    }

    public NodeTree getResultWithMinimalBorder( int level) throws IOException {
        System.out.println("["+level+"]"+"=============================");
        System.out.println("["+level+"]"+"Get Result with Minimal Border for Object with cost="+resulter.getTotalCost() ) ;
        System.out.println("["+level+"]"+"I have "+childs.size()+" childs.");
        //System.in.read() ;
        if( childs.size() == 0 ) {
            System.out.println("["+level+"]"+"Minimal is root\n\n");
            return this ;
        }
        NodeTree min = null ;
        int minimal = Integer.MAX_VALUE ;
        for( NodeTree node : childs ) {
            System.out.println("["+level+"]"+"Check child with cost="+node.getResulter().getTotalCost());
            NodeTree res = node.getResultWithMinimalBorder(level+1) ;
            if( res.getResulter().getTotalCost()<minimal ) {
                minimal = res.getResulter().getTotalCost() ;
                min = res ;
                System.out.println("["+level+"]"+"I find child with more less cost.");
            }
        }
        System.out.println("["+level+"]"+"Return result with cost="+min.getResulter().getTotalCost()+"\n\n");
        return min ;
    }
    
    public void addChilds( Collection<Resulter> collection) {
        System.out.println("***My cost is "+resulter.getTotalCost()+" i add "+collection.size()+" childs.");
        for( Resulter res : collection ) {
            childs.add( new NodeTree( res ) );
        }
    }
    
    public Resulter getFinishResult() {
        if ( resulter.isResult() )
            return resulter ;
        
        Resulter res = null ;
        for( NodeTree node : childs ) {
            res = node.getFinishResult() ;
            if( res != null )
                return res ;
        }
        return res ;
    }
}
